﻿//using FeatureManagement;
using Microsoft.AspNetCore.Authorization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.EventBus.Distributed;
using Volo.Abp.Features;
using Volo.Abp.MultiTenancy;
using Xms.Abp.Application.Services;
using Xms.Abp.Authorization;
using Xms.Abp.Data;
using Xms.Abp.Domain.Repositories;

namespace MemberManagement;

[Authorize]
[PermissionsUse(typeof(MemberManagementPermissions.Tenants))]
public class MemberAppService : XmsCrudAppService<Member, MemberResult, Guid, MembersPagedParameter, MemberCreateParameter, MemberUpdateParameter>, IMemberAppService
{
    protected IDistributedEventBus DistributedEventBus => LazyInject<IDistributedEventBus>();
    //protected IFeatureManagementStore FeatureStore => LazyInject<IFeatureManagementStore>();
    public MemberAppService(IXmsRepository<Member, Guid> repository) : base(repository)
    {
    }

    protected virtual string ManageFeaturesPolicyName => GetPolicy();

    protected override Func<MemberCreateParameter, Member> EntityCreator
        => input => new Member(GuidGenerator.Create(), input.Name, input.DisplayName);

    protected override async Task<IQueryable<Member>> CreateFilteredQueryAsync(MembersPagedParameter input)
    {
        if (input.Sorting.IsNullOrWhiteSpace())
        {
            input.Sorting = nameof(Member.Name);
        }
        return (await base.CreateFilteredQueryAsync(input))
            .WhereIf(!input.Filter.IsNullOrWhiteSpace(), r => r.No == input.Filter || r.PhoneNumber == input.Filter || r.Name.Contains(input.Filter));
    }

    protected override async Task AfterCreateAsync(Member entity, MemberCreateParameter input)
    {
        await DistributedEventBus.PublishAsync(new TenantCreatedEto
        {
            Id = entity.Id,
            Name = entity.Name,
            Properties =
            {
                { nameof(input.AdminEmailAddress), input.AdminEmailAddress },
                { nameof(input.AdminPhoneNumber), input.AdminPhoneNumber },
                { nameof(input.AdminPassword), input.AdminPassword }
            }
        });
    }

    //public async Task<IEnumerable<NameValue>> GetFeaturesAsync(Guid id)
    //{
    //    var features = await FeatureStore.GetAllAsync(TenantFeatureValueProvider.ProviderName, id.ToString());
    //    return features;
    //}

    //public async Task UpdateFeaturesAsync(Guid id, IEnumerable<NameValue> nameValues)
    //{
    //    await FeatureStore.SetAsync(TenantFeatureValueProvider.ProviderName, id.ToString(), nameValues.Select(r => new FeatureNameValue(r.Name, r.Value)).ToList());
    //}

    //public async Task DeleteAllFeaturesAsync(Guid id)
    //{
    //    await FeatureStore.DeleteAllAsync(TenantFeatureValueProvider.ProviderName, id.ToString());
    //}
}
